/*
 * This file is part of the MicroPython project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013-2018 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <stdint.h>
#include <string.h>

#include "py/runtime.h"
#include "py/mperrno.h"

#include "extmod/vfs.h"
#include "extmod/vfs_lfs.h"
#include "mod/machine.h"

#include "storage.h"
#include "wm_hal.h"


#if MICROPY_HW_ENABLE_STORAGE

#define MICROPY_HW_BDEV_IOCTL flash_bdev_ioctl

// ioctl, 如果要添加spi-flash支持, 修改本函数
int32_t flash_bdev_ioctl(uint32_t op, uint32_t arg)
{
    switch(op){
    case MP_BLOCKDEV_IOCTL_INIT:         // 1
        return 0;
        
    case MP_BLOCKDEV_IOCTL_DEINIT:       // 2
        return 0;
        
    case MP_BLOCKDEV_IOCTL_SYNC:         // 3
        return 0;
        
    case MP_BLOCKDEV_IOCTL_BLOCK_COUNT:  // 4
        return MICROPY_HW_BLK_CNT;
        
    case MP_BLOCKDEV_IOCTL_BLOCK_SIZE:   // 5
        return MICROPY_HW_BLK_SIZE;

    case MP_BLOCKDEV_IOCTL_BLOCK_ERASE:  // 6
        // 片内FLASH不需要擦除, HAL_FLASH_Write自行处理
        return 0;
    }
    return -MP_EINVAL;
}

static bool storage_is_initialised = false;

void storage_init(void) {
    if (!storage_is_initialised) {
        storage_is_initialised = true;
        MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_INIT, 0);
    }
}

void storage_flush(void) {
    MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_SYNC, 0);
}


uint32_t storage_get_block_size(void) {
    return FLASH_BLOCK_SIZE;
}

uint32_t storage_get_block_count(void) {
    return MICROPY_HW_BDEV_IOCTL(MP_BLOCKDEV_IOCTL_BLOCK_COUNT, 0);
}

// pybcnv2/mpconfigboard.h:
// #define MICROPY_HW_BDEV_READBLOCKS(dest, bl, n) spi_bdev_readblocks(&spi_bdev, (dest), (bl), (n))
// #define MICROPY_HW_BDEV_WRITEBLOCKS(src, bl, n) spi_bdev_writeblocks(&spi_bdev, (src), (bl), (n))
// 
int storage_read_blocks(uint8_t *dest, uint32_t block_num, uint32_t num_blocks) {
    #if defined(MICROPY_HW_BDEV_READBLOCKS)
    if (FLASH_PART1_START_BLOCK <= block_num && block_num + num_blocks <= FLASH_PART1_START_BLOCK + MICROPY_HW_BDEV_IOCTL(MP_BLOCKDEV_IOCTL_BLOCK_COUNT, 0)) {
        return MICROPY_HW_BDEV_READBLOCKS(dest, block_num, num_blocks);
    }
    #endif

    #if defined(MICROPY_HW_BDEV2_READBLOCKS)
    if (FLASH_PART2_START_BLOCK <= block_num && block_num + num_blocks <= FLASH_PART2_START_BLOCK + MICROPY_HW_BDEV2_IOCTL(MP_BLOCKDEV_IOCTL_BLOCK_COUNT, 0)) {
        return MICROPY_HW_BDEV2_READBLOCKS(dest, block_num, num_blocks);
    }
    #endif
    for (size_t i = 0; i < num_blocks; i++) {
        if (HAL_FLASH_Read((block_num + i) * FLASH_BLOCK_SIZE, (uint8_t*)dest + i * FLASH_BLOCK_SIZE, FLASH_BLOCK_SIZE) != HAL_OK) {
            return -MP_EIO; // error
        }
    }
    return 0; // success
}

int storage_write_blocks(const uint8_t *src, uint32_t block_num, uint32_t num_blocks) {
    #if defined(MICROPY_HW_BDEV_WRITEBLOCKS)
    if (FLASH_PART1_START_BLOCK <= block_num && block_num + num_blocks <= FLASH_PART1_START_BLOCK + MICROPY_HW_BDEV_IOCTL(MP_BLOCKDEV_IOCTL_BLOCK_COUNT, 0)) {
        return MICROPY_HW_BDEV_WRITEBLOCKS(src, block_num, num_blocks);
    }
    #endif

    #if defined(MICROPY_HW_BDEV2_WRITEBLOCKS)
    if (FLASH_PART2_START_BLOCK <= block_num && block_num + num_blocks <= FLASH_PART2_START_BLOCK + MICROPY_HW_BDEV2_IOCTL(MP_BLOCKDEV_IOCTL_BLOCK_COUNT, 0)) {
        return MICROPY_HW_BDEV2_WRITEBLOCKS(src, block_num, num_blocks);
    }
    #endif
    for (size_t i = 0; i < num_blocks; i++) {
        if (HAL_FLASH_Write((block_num + i) * FLASH_BLOCK_SIZE, (uint8_t*)src + i * FLASH_BLOCK_SIZE, FLASH_BLOCK_SIZE) != HAL_OK) {
            return -MP_EIO; // error
        }
    }
    return 0; // success
}

// 从特定位置(扇区号+偏移)开始读数据
int flash_bdev_readblocks_ext(uint8_t *dest, uint32_t block_num, uint32_t block_offset, uint32_t num_bytes) 
{
    return (HAL_FLASH_Read(block_num * FLASH_BLOCK_SIZE + block_offset, (uint8_t*)dest, num_bytes) == HAL_OK) ? (0) : (-1);
}

// 从特定位置(扇区号+偏移)开始写数据
int flash_bdev_writeblocks_ext(const uint8_t *src, uint32_t block_num, uint32_t block_offset, uint32_t num_bytes) 
{
    return (HAL_FLASH_Write(block_num * FLASH_BLOCK_SIZE + block_offset, (uint8_t*)src, num_bytes) == HAL_OK) ? (0) : (-1);
}

// 从特定位置(物理地址)读数据
int storage_read(uint8_t* dest, uint32_t addr, uint32_t num_bytes)
{
    return (HAL_FLASH_Read(addr, dest, num_bytes) == HAL_OK) ? (0) : (-1);
}


// 从特定位置(物理地址)写数据
int storage_write(const uint8_t *src, uint32_t addr, uint32_t num_bytes) 
{
    return (HAL_FLASH_Write(addr, (uint8_t*)src, num_bytes) == HAL_OK) ? (0) : (-1);
}


/******************************************************************************/
// MicroPython bindings
//
// Expose the flash as an object with the block protocol.

#ifdef MICROPY_HW_BDEV_SPIFLASH_EXTENDED
// Board defined an external SPI flash for use with extended block protocol
#define SPIFLASH (MICROPY_HW_BDEV_SPIFLASH_EXTENDED)
#define PYB_FLASH_NATIVE_BLOCK_SIZE (MP_SPIFLASH_ERASE_BLOCK_SIZE)
#define MICROPY_HW_BDEV_READBLOCKS_EXT(dest, bl, off, len) (spi_bdev_readblocks_raw(SPIFLASH, (dest), (bl), (off), (len)))
#define MICROPY_HW_BDEV_WRITEBLOCKS_EXT(dest, bl, off, len) (spi_bdev_writeblocks_raw(SPIFLASH, (dest), (bl), (off), (len)))

#elif (MICROPY_VFS_LFS1 || MICROPY_VFS_LFS2) && MICROPY_HW_ENABLE_INTERNAL_FLASH_STORAGE
// Board uses littlefs and internal flash, so enable extended block protocol on internal flash
#define PYB_FLASH_NATIVE_BLOCK_SIZE (FLASH_BLOCK_SIZE)
#define MICROPY_HW_BDEV_READBLOCKS_EXT(dest, bl, off, len) (flash_bdev_readblocks_ext((dest), (bl), (off), (len)))
#define MICROPY_HW_BDEV_WRITEBLOCKS_EXT(dest, bl, off, len) (flash_bdev_writeblocks_ext((dest), (bl), (off), (len)))
#endif

#ifndef PYB_FLASH_NATIVE_BLOCK_SIZE
#define PYB_FLASH_NATIVE_BLOCK_SIZE (FLASH_BLOCK_SIZE)
#endif


typedef struct _flash_obj_t{
    mp_obj_base_t base;
    uint32_t blk_start;      // 起始块号(对应物理块号)
    uint32_t blk_offs;       // 偏移块号, 从0开始, 实际块号是blk_start + blk_offs
    uint32_t blk_cnt;        // 块数量, blk_offs + blk_cnt不能大于总块数(或分区总块数)
}flash_obj_t;


// This Flash object represents the entire available flash, with emulated partition table at start
const flash_obj_t flash_obj = {
    { &flash_type },
    FLASH_PART1_START_BLOCK,       // 物理块号
    0,                             // 块号偏移, 实际块号=物理块号+块号偏移
    FLASH_PART1_BLK_CNT,           // 实际块数量, 这是个单例, 用于访问整个flash
};

STATIC void pyb_flash_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
    flash_obj_t *self = MP_OBJ_TO_PTR(self_in);
    if (self == &flash_obj) {
        mp_printf(print, "Flash()");
    } else {
        mp_printf(print, "Flash(blk_start=%u, blk_offs=%u, blk_cnt=%u)", self->blk_start, self->blk_offs, self->blk_cnt);
    }
}

STATIC mp_obj_t pyb_flash_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
    // Parse arguments
    enum { ARG_blk_offs, ARG_blk_cnt };
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_blk_offs,  MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
        { MP_QSTR_blk_cnt,   MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
    };
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
    if (args[ARG_blk_offs].u_int == -1 && args[ARG_blk_cnt].u_int == -1) {
        // Default singleton object that accesses entire flash, including virtual partition table
        return MP_OBJ_FROM_PTR(&flash_obj);
    }
    flash_obj_t *self = m_new_obj(flash_obj_t);
    self->base.type = &flash_type;
    self->blk_start = FLASH_PART1_START_BLOCK;
    
    mp_int_t blk_offs = args[ARG_blk_offs].u_int;
    mp_int_t blk_cnt = args[ARG_blk_cnt].u_int;
    mp_int_t max_blk_cnt = storage_get_block_count();
    
    //printf("bl_len:%d, start:%d, start%%PYB_FLASH_NATIVE_BLOCK_SIZE:%d\n", bl_len, start, start % PYB_FLASH_NATIVE_BLOCK_SIZE);
    if (blk_offs == -1) {
        blk_offs = 0;
    } else if (blk_offs < 0 || blk_offs > max_blk_cnt) {
        mp_raise_ValueError(MP_ERROR_TEXT("arg blk_offs should >= 0 and blk_offs < max_blk_cnt"));
    }
    if (blk_cnt == -1) {
        blk_cnt = max_blk_cnt - blk_offs - self->blk_start;
    } else if (blk_cnt <= 0 || blk_offs + blk_cnt > max_blk_cnt ) {
        mp_raise_ValueError(MP_ERROR_TEXT("arg blk_cnt should > 0 and blk_offs + blk_cnt <= max_blk_cnt "));
    }
    
    self->blk_offs = blk_offs;
    self->blk_cnt = blk_cnt;

    return MP_OBJ_FROM_PTR(self);
}

STATIC mp_obj_t pyb_flash_readblocks(size_t n_args, const mp_obj_t *args) {
    flash_obj_t *self = MP_OBJ_TO_PTR(args[0]);
    uint32_t block_num = mp_obj_get_int(args[1]);
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_WRITE);
    mp_uint_t ret = -MP_EIO;

    // Extended block read on a sub-section of the flash storage           
    uint32_t offset = mp_obj_get_int(args[3]);
    
    if(self->blk_offs + block_num <= self->blk_cnt && offset < FLASH_BLOCK_SIZE){
        block_num = self->blk_start + self->blk_offs + block_num;
        ret = MICROPY_HW_BDEV_READBLOCKS_EXT(bufinfo.buf, block_num, offset, bufinfo.len);
    }
    return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_flash_readblocks_obj, 3, 4, pyb_flash_readblocks);

STATIC mp_obj_t pyb_flash_writeblocks(size_t n_args, const mp_obj_t *args) {
    flash_obj_t *self = MP_OBJ_TO_PTR(args[0]);
    uint32_t block_num = mp_obj_get_int(args[1]);
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ);
    mp_uint_t ret = -MP_EIO;
    
    // Extended block write on a sub-section of the flash storage
    uint32_t offset = mp_obj_get_int(args[3]);
    if(self->blk_offs + block_num <= self->blk_cnt && offset < FLASH_BLOCK_SIZE){
        block_num = self->blk_start + self->blk_offs + block_num;
        ret = MICROPY_HW_BDEV_WRITEBLOCKS_EXT(bufinfo.buf, block_num, offset, bufinfo.len);
    }
    return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_flash_writeblocks_obj, 3, 4, pyb_flash_writeblocks);

STATIC mp_obj_t pyb_flash_ioctl(mp_obj_t self_in, mp_obj_t cmd_in, mp_obj_t arg_in) {
    flash_obj_t *self = self_in;
    mp_int_t cmd = mp_obj_get_int(cmd_in);
    switch (cmd) {
        case MP_BLOCKDEV_IOCTL_INIT: {
            mp_int_t ret = 0;
            storage_init();
            //if (mp_obj_get_int(arg_in) == 1) {
            //    // Will be using extended block protocol
            //    ;
            //}
            return MP_OBJ_NEW_SMALL_INT(ret);
        }
        case MP_BLOCKDEV_IOCTL_DEINIT: 
            storage_flush(); 
            return MP_OBJ_NEW_SMALL_INT(0); // TODO properly
        
        case MP_BLOCKDEV_IOCTL_SYNC: 
            storage_flush(); 
            return MP_OBJ_NEW_SMALL_INT(0);

        case MP_BLOCKDEV_IOCTL_BLOCK_COUNT:
            return MP_OBJ_NEW_SMALL_INT(self->blk_cnt);

        case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: 
            return MP_OBJ_NEW_SMALL_INT(FLASH_BLOCK_SIZE);
 
        case MP_BLOCKDEV_IOCTL_BLOCK_ERASE: {
            int ret = 0;
            #if defined(SPIFLASH)
            if (self->use_native_block_size) {
                mp_int_t block_num = self->start / PYB_FLASH_NATIVE_BLOCK_SIZE + mp_obj_get_int(arg_in);
                ret = spi_bdev_ioctl(SPIFLASH, BDEV_IOCTL_BLOCK_ERASE, block_num);
            }
            #endif
            return MP_OBJ_NEW_SMALL_INT(ret);
        }

        default: return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_flash_ioctl_obj, pyb_flash_ioctl);

STATIC const mp_rom_map_elem_t pyb_flash_locals_dict_table[] = {
    { MP_ROM_QSTR(MP_QSTR_blk_start), MP_ROM_PTR(MP_OBJ_NEW_SMALL_INT(FLASH_PART1_START_BLOCK)) },   // 起始块号,make_new(start=blk_start*blk_size)
    { MP_ROM_QSTR(MP_QSTR_blk_cnt), MP_ROM_PTR(MP_OBJ_NEW_SMALL_INT(MICROPY_HW_BLK_CNT)) },          // 结束块号, make_new(start=blk_start*blk_size, len=blk_cnt*blk_size)
    { MP_ROM_QSTR(MP_QSTR_blk_size), MP_ROM_PTR(MP_OBJ_NEW_SMALL_INT(MICROPY_HW_BLK_SIZE)) },        // 块大小(擦除单位)                
    
    { MP_ROM_QSTR(MP_QSTR_readblocks), MP_ROM_PTR(&pyb_flash_readblocks_obj) },
    { MP_ROM_QSTR(MP_QSTR_writeblocks), MP_ROM_PTR(&pyb_flash_writeblocks_obj) },
    { MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&pyb_flash_ioctl_obj) },
};

STATIC MP_DEFINE_CONST_DICT(pyb_flash_locals_dict, pyb_flash_locals_dict_table);

const mp_obj_type_t flash_type = {
    { &mp_type_type },
    .name = MP_QSTR_Flash,
    .print = pyb_flash_print,
    .make_new = pyb_flash_make_new,
    .locals_dict = (mp_obj_dict_t*)&pyb_flash_locals_dict,
};

#endif
